
package com.parsechina.hpush.broker.internal.subscriptions;

import com.parsechina.hpush.broker.spi.ISessionsStore;
import io.netty.handler.codec.mqtt.MqttQoS;

import java.io.Serializable;
import java.util.Objects;

/**
 * Maintain the information about which Topic a certain ClientID is subscribed
 * and at which QoS
 *
 * @author andrea
 */
public final class Subscription implements Serializable {

    private static final long serialVersionUID = -535493959751679807L;
    /**
     * max QoS acceptable
     */
    private final MqttQoS requestedQos;
    private final String clientId;
    private final boolean active;

    final String topicFilter;

    public Subscription(String clientId, String topicFilter, MqttQoS requestedQos) {
        this.requestedQos = requestedQos;
        this.clientId = clientId;
        this.topicFilter = topicFilter;
        active = true;
    }

    public Subscription(Subscription orig) {
        requestedQos = orig.requestedQos;
        clientId = orig.clientId;
        topicFilter = orig.topicFilter;
        active = orig.active;
    }

    public String getClientId() {
        return clientId;
    }

    public MqttQoS getRequestedQos() {
        return requestedQos;
    }

    public String getTopicFilter() {
        return topicFilter;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Subscription that = (Subscription) o;
        return active == that.active &&
                requestedQos == that.requestedQos &&
                Objects.equals(clientId, that.clientId) &&
                Objects.equals(topicFilter, that.topicFilter);
    }

    @Override
    public int hashCode() {
        return Objects.hash(requestedQos, clientId, topicFilter, active);
    }

    @Override
    public String toString() {
        return "Subscription{" +
                "requestedQos=" + requestedQos +
                ", clientId='" + clientId + '\'' +
                ", topicFilter='" + topicFilter + '\'' +
                ", active=" + active +
                '}';
    }

    @Override
    public Subscription clone() {
        try {
            return (Subscription) super.clone();
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }

    public ISessionsStore.ClientTopicRelation asClientTopicCouple() {
        return new ISessionsStore.ClientTopicRelation(clientId, topicFilter);
    }
}
